package com.myWeb.dao.impl;

import com.myWeb.beans.User;
import com.myWeb.dao.IUserDao;
import com.myWeb.utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class userDao implements IUserDao {
    private PreparedStatement ps;
    private ResultSet rs;
    //保存用户信息
    @Override
    public void saveUser(User user) throws SQLException, ClassNotFoundException {
        Connection conn = DBUtil.getConnection();
        String sql = "insert into db_user values(?,?,?,?)";
        ps = conn.prepareStatement(sql);
        ps.setString(1,user.getName());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getEmail());
        ps.setString(4,user.getTelephone());
        ps.execute();
        if(ps != null){
            ps.close();
        }
        if(conn != null){
            conn.close();
        }
    }
    //判断是否已经注册
    @Override
    public boolean isExist(String username) throws SQLException, ClassNotFoundException {
//      System.out.println(username);
        boolean flag = false;
        Connection conn = DBUtil.getConnection();
        String sql = "select name from db_user where name = ?";
        ps = conn.prepareStatement(sql);
        ps.setString(1,username);
        rs = ps.executeQuery();
        if(rs.next()){
            flag = true;
        }
        return flag;
    }

    //判断用户是否可以登录
    @Override
    public boolean canLogin(User user) throws SQLException, ClassNotFoundException {
        boolean flag = true;
        Connection conn = DBUtil.getConnection();
        String sql = "select name from db_user where name = ? and password = ?";
        ps = conn.prepareStatement(sql);
        System.out.println(user.getName());
        ps.setString(1,user.getName());
        ps.setString(2,user.getPassword());
        rs = ps.executeQuery();
        if(rs.next()){
            flag = true;
        }else{
            flag = false;
        }
        if(rs != null){
            rs.close();
        }
        return flag;
    }
}
